
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfoApi } from '@/api/user'
import { Message } from 'element-ui'
import router from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {}
    }
  },
  mutations: {
    // 1.存token
    SET_TOKEN(state, token) {
      // 往本地存
      setToken(token)
      // 2 往state存
      state.token = token
    },
    //  设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    clearUserInfo(state) {
    // 清除Token
      state.token = ''
      removeToken()
    }
  },
  actions: {
    // context上下文，传入参数
    async login(context, { username, password }) {
      // // todo: 调用登录接口
      const res = await login({ username, password })
      context.commit('SET_TOKEN', res.data.token)
      Message.success('登录成功~')
      // 1.2 跳转到首页
      router.replace('/')
    },
    // 获取用户信息
    async getUserInfo(context) {
      const userInfo = await getUserInfoApi()
      context.commit('SET_USER_INFO', userInfo)
    }
  }
}

